import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

///
/// 工厂id
///
const String factoryID = 'vap_plugin/video_plugin_view';

///
/// 通道名字
///
const String methodChannelName = 'com.vap_plugin.ultra.FlutterView_';

///
/// 播放结束的回调
///
typedef PlayEndCallback = void Function();

class VapPluginView extends StatefulWidget {
  ///
  /// 播放结束的回调
  ///
  final PlayEndCallback playEndCallback;

  const VapPluginView({super.key, required this.playEndCallback});

  @override
  State<StatefulWidget> createState() {
    return VapPluginViewState();
  }
}

class VapPluginViewState extends State<VapPluginView> {
  ///
  /// 方法通道
  ///
  MethodChannel? _methodChannel;

  @override
  Widget build(BuildContext context) {
    if (Platform.isAndroid) {
      return AndroidView(
        viewType: factoryID,
        layoutDirection: TextDirection.ltr,
        onPlatformViewCreated: (id) {
          _methodChannel = MethodChannel('$methodChannelName$id');
        },
      );
    } else if (Platform.isIOS) {
      return UiKitView(
        viewType: factoryID,
        layoutDirection: TextDirection.ltr,
        onPlatformViewCreated: (id) {
          _methodChannel = MethodChannel('$methodChannelName$id');
        },
      );
    }
    return Container();
  }

  playByPath(Map<String, dynamic> params) {
    _methodChannel?.invokeMethod('playPath', params).then((dict) {
      //["status":"playFail","msg":error.localizedDescription]
      if (dict is Map) {
        if (dict['status'] == 'playEnd') {
          widget.playEndCallback();
        } else if (dict['status'] == 'playFail') {}
      }
    });
  }

  playByAsset(Map<String, dynamic> params) {
    _methodChannel?.invokeMethod('playAsset', params).then((dict) {
      if (dict is Map) {
        if (dict['status'] == 'playEnd') {
          widget.playEndCallback();
        } else if (dict['status'] == 'playFail') {}
      }
    });
  }

  // pausePlay() {
  // _methodChannel?.invokeMethod('pausePlay', {}).then((value) {});
  // }

  // resumePlay() {
  // _methodChannel?.invokeMethod('resumePlay', {}).then((value) {});
  // }

  stopPlay() {
    _methodChannel?.invokeMethod('stopPlay', {}).then((value) {});
  }

  manualDestroy() {
    _methodChannel?.invokeMethod('manualDestroy', {}).then((value) {});
  }
}
